package cn.msqweb.filter;

import cn.msqweb.config.WhiteUrlsConfig;
import cn.msqweb.constant.AuthConstants;
import cn.msqweb.constant.BusinessEnum;
import cn.msqweb.model.Result;
import cn.msqweb.util.JwtJson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.util.Date;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        //判断请求地址是否是白名单
        if (whiteUrlsConfig.getAllowUrls().contains(path)){
            return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        //判断authorization 是否为空
        if (StringUtils.hasText(authorization)){
            //获取token
            String token = authorization.replaceFirst(AuthConstants.BEARER, "");
            //判断token是否有效
            System.out.println("token = " + token);
            if (StringUtils.hasText(token) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + token) && JwtJson.verifyJWT(token)){
                return chain.filter(exchange);
            }
        }
        log.error("拦截非法请求，时间{}，请求的API路径：{}",new Date(),path);
        ServerHttpResponse response = exchange.getResponse();
        ObjectMapper objectMapper =new ObjectMapper();
        Result<Object> fail = Result.fail(BusinessEnum.OPERATION_FAIL);
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(fail);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);

        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
